/*
 * @Author: xiaotiwen
 * @Date: 2020-05-12 11:25:56
 * @LastEditTime: 2020-07-11 19:11:02
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\commonMixins.js
 * @Description: 实习管理公共mixins
 */

import {
    queryDic
} from 'common/src/api/dictionary';
import {
    btnSet
} from 'common/src/api/practiceManagement/scheduleSetting';
export default {
    data() {
        return {
            auditStatus: [{
                    label: '提交',
                    value: 'COMMIT',
                    types: 'warning'
                },
                {
                    label: '通过',
                    value: 'Process',
                    types: 'success'
                },
                {
                    label: '结束',
                    value: 'End',
                    types: 'info'
                },
                {
                    label: '已驳回',
                    value: 'Reject',
                    types: 'danger'
                },
                {
                    label: '撤回',
                    value: 'Recall',
                    types: 'warning'
                }
            ]
        };
    },
    computed: {
        changeType() {
            return function (val, data) {
                let status = '';
                data.forEach(item => {
                    if (item.value === val || parseInt(item.value) === parseInt(val)) {
                        status = item.label;
                        return false;
                    }
                });
                return status;
            };
        },
        fieldChange() {
            return function (arr, val, fields = []) { // fields =['label', 'value']特别的指定翻译，默认label，value。 val需要翻译的字， arr翻译的字典组
                let label = 'label';
                let value = 'value';
                let changes = '';
                if (fields.length > 0) {
                    label = fields[0];
                    value = fields[1];
                }
                arr.forEach(item => {
                    if (item[value] === val || parseInt(item[value]) === parseInt(val)) {
                        changes = item[label];
                        return false;
                    }
                });
                return changes;
            };
        }
    },
    methods: {
        timeSetBtns(yearTerms) {
            let flags = false;
            return new Promise((resolve) => {
                btnSet({
                    yearTerm: yearTerms
                }).then(res => {
                    if (res && res.code !== 200) {
                        this.message({
                            message: res.msg,
                            type: 'warning'
                        });
                        return flags;
                    } else if (res.data) {
                        let start = new Date(res.data.cosArrangeStartDate).getTime();
                        let end = new Date(res.data.cosArrangeEndDate).getTime();
                        let now = new Date().getTime();
                        if (now > start) {
                            if (!res.data.cosArrangeEndDate) {
                                flags = true;
                            } else if (now < end) {
                                flags = true;
                            }
                        }
                    }
                    if (!flags) {
                        this.$eduAlert('当前时间不在排课时间内', '提示')
                    }
                    resolve(flags)
                });
            });
        },
        reworkBtns(yearTerms) {
            let flags = false;
            return new Promise((resolve) => {
                btnSet({
                    yearTerm: yearTerms
                }).then(res => {
                    if (res && res.code !== 200) {
                        this.message({
                            message: res.msg,
                            type: 'warning'
                        });
                        return flags;
                    } else if (res.data) {
                        let start = new Date(res.data.practiceRetakeStartDate).getTime();
                        let end = new Date(res.data.practiceRetakeEndDate).getTime();
                        let now = new Date().getTime();
                        if (now > start) {
                            if (!res.data.practiceRetakeEndDate) {
                                flags = true;
                            } else if (now < end) {
                                flags = true;
                            }
                        }
                    }
                    if (!flags) {
                        this.$eduAlert('当前时间不在重修排课时间内', '提示')
                    }
                    resolve(flags)
                });
            });
        },
        fundTimeSetBtns(yearTerms) {
            let flags = false;
            return new Promise((resolve) => {
                btnSet({
                    yearTerm: yearTerms
                }).then(res => {
                    if (res && res.code !== 200) {
                        this.message({
                            message: res.msg,
                            type: 'warning'
                        });
                        return flags;
                    } else if (res.data) {
                        let start = new Date(res.data.expenseReiburStartDate).getTime();
                        let end = new Date(res.data.expenseReiburEndDate).getTime();
                        let now = new Date().getTime();
                        if (now > start) {
                            if (!res.data.expenseReiburEndDate) {
                                flags = true;
                            } else if (now < end) {
                                flags = true;
                            }
                        }
                    }
                    if (!flags) {
                        this.$eduAlert('当前时间不在经费报销时间内', '提示')
                    }
                    resolve(flags)
                });
            });
        },
        // 数字转换  1 ==> 01 digit位数，默认2位
        numberDigits(val, digit = 2) {
            let nums = '0000000000000' + val;
            nums = nums.substring(nums.length - digit); // 输出001就-3
            return nums;
        },
        getSortFun(order, sortBy) { // 数组中根据某个字段排序， order asc正序 sortBy依据排序的字段
            var ordAlpah = (order == 'asc') ? '>' : '<';
            var sortFun = new Function('a', 'b', 'return parseInt(a.' + sortBy + ')' + ordAlpah + 'parseInt(b.' + sortBy + ')' + '?1:-1');
            return sortFun;
        },
        initOptions(val) { // val: {  X_PYCC: 'trainingLevel',   G_ZY: 'profession'} // 专业
            let keys = Object.keys(val);
            const data = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: keys
            };
            return new Promise((resolve, reject) => {
                queryDic(data).then(res => {
                    if (res.code === 200) {
                        keys.forEach((item) => {
                            this._fill(val[item], res.data[item]);
                        });
                    }
                    resolve(this.options);
                }).catch((err) => {
                    reject(err);
                });
            });
        },
        _fill(type, data) {
            for (const key in data) {
                this.options[type].push({
                    value: key,
                    label: data[key]
                });
            }
        },
        // 联动筛选
        filterOptions(data, vals, keyObj = {}) { // keyAll: {X_YX: 'faculty',X_YX: 'faculty'} vals { value: 123, type: XY2ZY}
            let keys = Object.keys(data);
            this.options[data[keys[0]]] = [];
            this.queryForm[data[keys[0]]] = '';
            let filter = {
                prefix: [vals.value],
                specilaCode: vals.type
            };
            if (JSON.stringify(keyObj) !== '{}') {
                let arr1 = Object.keys(keyObj);
                arr1.forEach(item => {
                    this.$set(filter, item, this.queryForm[keyObj[item]]);
                });
            }
            let datas = {
                lang: this.$store.getters.language || 'cn',
                type: 'allChild',
                keys: keys,
                filter: filter
            };
            queryDic(datas).then(res => {
                if (res.code === 200) {
                    this._fill(data[keys[0]], res.data[keys[0]]);
                }
            });
        },
        formatDate(date, fmt) { // 时间转换列如 fmt yyyy-mm-dd
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            let o = {
                'M+': date.getMonth() + 1,
                'd+': date.getDate(),
                'h+': date.getHours(),
                'm+': date.getMinutes(),
                's+': date.getSeconds()
            };
            for (let k in o) {
                if (new RegExp(`(${k})`).test(fmt)) {
                    let str = o[k] + '';
                    fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ('00' + str).substr(str.length));
                }
            }
            return fmt;
        },
        convertCurrency(money) { // 阿拉伯数字自动转换为中文钱
            // 汉字的数字
            let cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
            // 基本单位
            let cnIntRadice = new Array('', '拾', '佰', '仟');
            // 对应整数部分扩展单位
            let cnIntUnits = new Array('', '万', '亿', '兆');
            // 对应小数部分单位
            let cnDecUnits = new Array('角', '分', '毫', '厘');
            // 整数金额时后面跟的字符
            let cnInteger = '整';
            // 整型完以后的单位
            let cnIntLast = '元';
            // 最大处理的数字
            let maxNum = 999999999999999.9999;
            // 金额整数部分
            let integerNum;
            // 金额小数部分
            let decimalNum;
            // 输出的中文金额字符串
            let chineseStr = '';
            // 分离金额后用的数组，预定义
            let parts;
            if (money === '') {
                return '';
            }
            money = parseFloat(money);
            if (money >= maxNum) {
                // 超出最大处理数字
                return '';
            }
            if (money === 0) {
                chineseStr = cnNums[0] + cnIntLast + cnInteger;
                return chineseStr;
            }
            // 转换为字符串
            money = money.toString();
            if (money.indexOf('.') === -1) {
                integerNum = money;
                decimalNum = '';
            } else {
                parts = money.split('.');
                integerNum = parts[0];
                decimalNum = parts[1].substr(0, 4);
            }
            // 获取整型部分转换
            if (parseInt(integerNum, 10) > 0) {
                let zeroCount = 0;
                let IntLen = integerNum.length;
                for (let i = 0; i < IntLen; i++) {
                    let n = integerNum.substr(i, 1);
                    let p = IntLen - i - 1;
                    let q = p / 4;
                    let m = p % 4;
                    if (n === '0') {
                        zeroCount++;
                    } else {
                        if (zeroCount > 0) {
                            chineseStr += cnNums[0];
                        }
                        // 归零
                        zeroCount = 0;
                        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
                    }
                    if (m === 0 && zeroCount < 4) {
                        chineseStr += cnIntUnits[q];
                    }
                }
                chineseStr += cnIntLast;
            }
            // 小数部分
            if (decimalNum !== '') {
                let decLen = decimalNum.length;
                for (let i = 0; i < decLen; i++) {
                    let n = decimalNum.substr(i, 1);
                    if (n !== '0') {
                        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
                    }
                }
            }
            if (chineseStr === '') {
                chineseStr += cnNums[0] + cnIntLast + cnInteger;
            } else if (decimalNum === '') {
                chineseStr += cnInteger;
            }
            return chineseStr;
        },
        // 必填输入框校验输入$符号
        validateInput (rule, value, callback) {
          if (value === '' || !value) {
            return callback(new Error(this.$t('inputPlaceholder')));
          } else if (value.includes('$')) {
            return callback(new Error(this.$t('achievementApply.specilTips')));
          }
          return callback();
        },
        // 非必填输入框校验$符号
        validateRemark (rule, value, callback) {
          if (value === '' || !value) {
            return callback();
          } else if (value.includes('$')) {
            return callback(new Error(this.$t('achievementApply.specilTips')));
          }
          return callback();
        },
        // 获取培养层次，仅保留博士选项
        getEdulevel() {
          const data = {
            lang: this.$store.getters.language || 'cn',
            type: 'allChild',
            keys: ['X_PYCC']
          };
          return new Promise((resolve, reject) => {
              queryDic(data).then(res => {
                  if (res.code === 200) {
                    this._fill('eduLevel', res.data['X_PYCC']);
                    this.options.eduLevel = this.options.eduLevel.filter(v => v.value === '6');
                  }
                  resolve(this.options);
              }).catch((err) => {
                  reject(err);
              });
          });
        },
    }
};
